package com.un.ebs.core.util;

import com.un.ebs.core.UserContext;
import com.un.ebs.core.UserContextService;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.exception.SystemException;
import io.jsonwebtoken.impl.DefaultClaims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @email 496382223@qq.com
 * @author:Lijj
 * @date: 2019/9/12
 */
@Component
public class SecurityUtils {

    private static ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        SecurityUtils.applicationContext = applicationContext;
    }

    /**
     * 从SpringSecurity中获取当前登陆用户
     *
     * @return
     */
    public static UserContext getUserContent() {
        Optional<UserContextService> tokenService = applicationContext.getBeansOfType(UserContextService.class).entrySet().stream().map(s -> s.getValue()).findFirst();
        if (!tokenService.isPresent()) {
            throw new BusinessException("TokenServer Not implement.");
        }
        return tokenService.get().getUserContext();
    }

    @Deprecated
    public static UserContext getUserContext(String token) {
        Map map = JwtUtils.parseToken(token);
        UsernamePasswordAuthenticationToken scObj = new UsernamePasswordAuthenticationToken(map, null, null);
        SecurityContextHolder.getContext().setAuthentication(scObj);
        return getUserContent();
    }

    public static String getTenantId() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication auth = context.getAuthentication();
        if (auth == null) {
            throw new SystemException("当前没有设置用户上下文!");
        }
        return ((DefaultClaims)auth.getPrincipal()).get("tenantId").toString();
    }

    /**
     * 设置SpringSecurity当前用户
     *
     * @param userContentDTO
     */
    public static void setUserContent(UserContext userContentDTO) {
        Map userContentMap = BeanUtils.beanToMap(userContentDTO);
        UsernamePasswordAuthenticationToken scObj = new UsernamePasswordAuthenticationToken(userContentMap, null, null);
        SecurityContextHolder.getContext().setAuthentication(scObj);
    }
}
